import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"
import qs from 'qs'

export const resginInterceptors = (instance: AxiosInstance): void => {
    // 添加请求拦截器
    instance.interceptors.request.use(function (config: AxiosRequestConfig) {
        // 在发送请求之前做些什么
        (config.headers as any)['content-type'] = "application/json";
        (config.headers as any)['Access-Control-Allow-Origin'] = '*';
        if (config.method === 'post' || config.method === 'POST') {
            if ((config.headers as any)['content-type'] === 'application/x-www-form-urlencoded') {
                config.data = qs.stringify(config.data)
            }
        }
        return config;
    }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });

    // 添加响应拦截器
    instance.interceptors.response.use(function (response: AxiosResponse) {
        // 对响应数据做点什么
        return response;
    }, function (error) {
        // 对响应错误做点什么
        const { status } = error.response as AxiosResponse;
        if (status === 401) {
            console.log('登录态过期')
        }
        return Promise.reject(error);
    });
}